<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="请输入关键字"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-button class="filter-item" type="primary" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="分类Key">
        <template #default="scope">
          {{ scope.row.categoryKey }}
        </template>
      </el-table-column>
      <el-table-column label="分类名称">
        <template #default="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column label="展示顺序" width="110" align="center">
        <template #default="scope">
          {{ scope.row.index }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
            {{ scope.row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template #default="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.createAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      :current-page="listQuery.current"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增分类' : '编辑分类'"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="分类Key" prop="categoryKey">
          <el-input v-model="temp.categoryKey" />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="temp.categoryName" />
        </el-form-item>
        <el-form-item label="展示顺序" prop="index">
          <el-input-number v-model="temp.index" :min="1" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getCategoryPage,
  addCategory,
  updateCategory,
  deleteCategory
} from '@/api/category';

// 数据列表
const list = ref([]);
const total = ref(0);
const listLoading = ref(true);
const dialogFormVisible = ref(false);
const dialogStatus = ref('');
const dataForm = ref(null);

// 查询参数
const listQuery = reactive({
  current: 1,
  size: 10,
  keyword: ''
});

// 表单数据
const temp = reactive({
  id: undefined,
  categoryKey: '',
  categoryName: '',
  index: 1,
  status: 'active',
  remark: ''
});

// 表单验证规则
const rules = {
  categoryKey: [{ required: true, message: '请输入分类Key', trigger: 'blur' }],
  categoryName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  index: [{ required: true, message: '请输入展示顺序', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取数据列表
const getList = () => {
  listLoading.value = true;
  getCategoryPage(listQuery)
    .then(response => {
      list.value = response.data.records;
      total.value = response.data.total;
      listLoading.value = false;
    })
    .catch(() => {
      listLoading.value = false;
    });
};

// 搜索
const handleFilter = () => {
  listQuery.current = 1;
  getList();
};

// 改变每页数量
const handleSizeChange = (val) => {
  listQuery.size = val;
  getList();
};

// 改变页码
const handleCurrentChange = (val) => {
  listQuery.current = val;
  getList();
};

// 重置表单
const resetTemp = () => {
  Object.assign(temp, {
    id: undefined,
    categoryKey: '',
    categoryName: '',
    index: 1,
    status: 'active',
    remark: ''
  });
};

// 新增
const handleCreate = () => {
  resetTemp();
  dialogStatus.value = 'create';
  dialogFormVisible.value = true;
  setTimeout(() => {
    if (dataForm.value) {
      dataForm.value.resetFields();
    }
  }, 0);
};

// 创建数据
const createData = () => {
  if (dataForm.value) {
    dataForm.value.validate((valid) => {
      if (valid) {
        addCategory(temp).then(() => {
          dialogFormVisible.value = false;
          ElMessage({
            message: '创建成功',
            type: 'success'
          });
          getList();
        });
      }
    });
  }
};

// 编辑
const handleUpdate = (row) => {
  Object.assign(temp, row);
  dialogStatus.value = 'update';
  dialogFormVisible.value = true;
};

// 更新数据
const updateData = () => {
  if (dataForm.value) {
    dataForm.value.validate((valid) => {
      if (valid) {
        updateCategory(temp).then(() => {
          dialogFormVisible.value = false;
          ElMessage({
            message: '更新成功',
            type: 'success'
          });
          getList();
        });
      }
    });
  }
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCategory(row.id).then(() => {
      ElMessage({
        message: '删除成功',
        type: 'success'
      });
      getList();
    });
  }).catch(() => {
    // 取消删除
  });
};

// 页面加载时获取数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
</style> 